package lauglog.util;

import java.sql.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import lauglog.bean.TodaysCommentsBean;

/*
 * This is a threaded class which runs 
 * in the background and constantly updates the 
 * comments bean, as users can be getting new 
 * comments while logged in.  It keeps repeating the same
 * sql query in a timed manner, it has private instance varialbes
 * to access the session objects and the id of the user.
 */

/**
 *
 * @author Waseem Mir
 */
public class CommentUpdate extends Thread implements HttpSessionBindingListener{
    
    //id associated with specific user, who's comments to update
    private int userID;
    
    //reference to session in which the comments bean will be placed
    private HttpSession session;
    
    //constructor for thread which sets the instance variables
    public CommentUpdate(int userID, HttpSession session)
    {
        this.userID = userID;
        this.session = session;
    }
    
    public void valueBound(HttpSessionBindingEvent event) {
        //start this thread as soon as its bound to the the session
        start();
    }

    public void valueUnbound(HttpSessionBindingEvent event) {
        //end this thread when the session expires for any reason
        interrupt();
    }
    
    //this is where the sql query that repeats will run
    public void run() {
        while(true)
        {
            //Initiate variables for database queries
            String url = "jdbc:mysql://localhost/lauglog";
            String dbUserName = "root";
            String dbPassword = "";
            String driver = "com.mysql.jdbc.Driver";

            Connection con = null;
            try{

                //Make the connection
                Class.forName(driver).newInstance();
                con = DriverManager.getConnection(url, dbUserName, dbPassword);

                //this sql statement will query the comments and users tables,
                //to get all comments sent to logged in user today, with the names
                //of the friends who have sent the comments
                PreparedStatement todaysCommentsStatement = con.prepareStatement("SELECT C.SenderId,C.Content,U.FirstName,U.LastName FROM comments C, users U WHERE C.ReceiverId = ? AND C.SenderId=U.UserId AND DATE(C.DateTime) = DATE(NOW())");
                todaysCommentsStatement.setInt(1, userID);
                ResultSet todaysCommentsRs = todaysCommentsStatement.executeQuery();

                //comments bean consists of a vector of comment objects
                //must make the vector with the result set then add to bean
                TodaysCommentsBean todaysCommentsBean = new TodaysCommentsBean();
                Vector<Comment> commentVector = new Vector();
                while(todaysCommentsRs.next()){

                    Comment c = new Comment();
                    c.setSenderID(todaysCommentsRs.getInt("SenderId"));
                    c.setContent(todaysCommentsRs.getString("Content"));
                    c.setSenderName(todaysCommentsRs.getString("FirstName")+" "+todaysCommentsRs.getString("LastName"));

                    commentVector.add(c);

                }

                //set vector of comments in todays comments bean
                todaysCommentsBean.setCommentList(commentVector);

                //replace the existing todaysComments bean with 
                //the updated one
                session.setAttribute("todaysComments",todaysCommentsBean);
                
                //if the thread is told to stop, stop it
                if (Thread.interrupted()) {
                    con.close();
                    return;
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try{
                    con.close();
                }catch(Exception e){

                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                //stop thread if told to stop
                return;
            }
        }
    }
}
